#include "wifi_board.h"
#include "audio_codecs/no_audio_codec.h"
#include "display/lcd_display.h"
#include "font_awesome_symbols.h"
#include "application.h"
#include "button.h"
#include "config.h"
#include "mcp_server.h"
#include "settings.h"

#include <wifi_station.h>
#include <esp_log.h>
#include <esp_lcd_panel_vendor.h>
#include <driver/i2c_master.h>
#include <driver/spi_common.h>
#include <driver/uart.h>
#include <cstring>

#include "esp32_camera.h"

#define TAG "esp-xiao"

LV_FONT_DECLARE(font_puhui_30_4);
LV_FONT_DECLARE(font_awesome_30_4);

class EspXiaoBot : public WifiBoard {
private:
    Button boot_button_;
    Display* display_;
    Esp32Camera* camera_;
    light_mode_t light_mode_ = LIGHT_MODE_ALWAYS_ON;


    void InitializeSpi() {
        spi_bus_config_t buscfg = {};
        buscfg.mosi_io_num = DISPLAY_MOSI_GPIO;
        buscfg.miso_io_num = GPIO_NUM_NC;
        buscfg.sclk_io_num = DISPLAY_CLK_GPIO;
        buscfg.quadwp_io_num = GPIO_NUM_NC;
        buscfg.quadhd_io_num = GPIO_NUM_NC;
        buscfg.max_transfer_sz = DISPLAY_WIDTH * DISPLAY_HEIGHT * sizeof(uint16_t);
        ESP_ERROR_CHECK(spi_bus_initialize(SPI3_HOST, &buscfg, SPI_DMA_CH_AUTO));
    }

    void InitializeButtons() {
        boot_button_.OnClick([this]() {
            auto& app = Application::GetInstance();
            if (app.GetDeviceState() == kDeviceStateStarting && !WifiStation::GetInstance().IsConnected()) {
                ResetWifiConfiguration();
            }
            app.ToggleChatState();
        });
    }

    void InitializeDisplay() {
        esp_lcd_panel_io_handle_t panel_io = nullptr;
        esp_lcd_panel_handle_t panel = nullptr;

        // 液晶屏控制IO初始化
        ESP_LOGD(TAG, "Install panel IO");
        esp_lcd_panel_io_spi_config_t io_config = {};
        io_config.cs_gpio_num = DISPLAY_CS_GPIO;
        io_config.dc_gpio_num = DISPLAY_DC_GPIO;
        io_config.spi_mode = 0;
        io_config.pclk_hz = 40 * 1000 * 1000;
        io_config.trans_queue_depth = 10;
        io_config.lcd_cmd_bits = 8;
        io_config.lcd_param_bits = 8;
        ESP_ERROR_CHECK(esp_lcd_new_panel_io_spi(SPI3_HOST, &io_config, &panel_io));

        // 初始化液晶屏驱动芯片
        ESP_LOGD(TAG, "Install LCD driver");

        esp_lcd_panel_dev_config_t panel_config = {};
        panel_config.reset_gpio_num = GPIO_NUM_NC;
        panel_config.rgb_ele_order = LCD_RGB_ELEMENT_ORDER_RGB;
        panel_config.bits_per_pixel = 16;

    #ifdef CONFIG_DISPLAY_USE_JBD013
        ESP_LOGI(TAG, "Install LCD JBD013");
        ESP_ERROR_CHECK(esp_lcd_new_panel_jbd013(panel_io, &panel_config, &panel));
    #elif CONFIG_DISPLAY_USE_M103
        ESP_ERROR_CHECK(esp_lcd_new_panel_jbd013(panel_io, &panel_config, &panel));
    #elif CONFIG_DISPLAY_USE_ST7789
        ESP_LOGI(TAG, "Install LCD ST7789");
        ESP_ERROR_CHECK(esp_lcd_new_panel_st7789(panel_io, &panel_config, &panel));
    #else 
        ESP_LOGI(TAG, "Install LCD GC9D01");
        ESP_ERROR_CHECK(esp_lcd_new_panel_gc9d01(panel_io, &panel_config, &panel));
    #endif

        
        esp_lcd_panel_reset(panel);
        esp_lcd_panel_init(panel);
        esp_lcd_panel_invert_color(panel, true);
        esp_lcd_panel_disp_on_off(panel, true);
        display_ = new SpiLcdDisplay(panel_io, panel,
                                    DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_OFFSET_X, DISPLAY_OFFSET_Y, DISPLAY_MIRROR_X, DISPLAY_MIRROR_Y, DISPLAY_SWAP_XY,
                                    {
                                        .text_font = &font_puhui_30_4,
                                        .icon_font = &font_awesome_30_4,
                                        .emoji_font = font_emoji_64_init(),
                                    });
    }

    void InitializeCamera() {
        camera_config_t camera_config = {};

        camera_config.pin_pwdn = XIAO_CAMERA_PWDN;
        camera_config.pin_reset = XIAO_CAMERA_RESET;
        camera_config.pin_xclk = XIAO_CAMERA_XCLK;
        camera_config.pin_pclk = XIAO_CAMERA_PCLK;
        camera_config.pin_sccb_sda = XIAO_CAMERA_SIOD;
        camera_config.pin_sccb_scl = XIAO_CAMERA_SIOC;

        camera_config.pin_d0 = XIAO_CAMERA_D0;
        camera_config.pin_d1 = XIAO_CAMERA_D1;
        camera_config.pin_d2 = XIAO_CAMERA_D2;
        camera_config.pin_d3 = XIAO_CAMERA_D3;
        camera_config.pin_d4 = XIAO_CAMERA_D4;
        camera_config.pin_d5 = XIAO_CAMERA_D5;
        camera_config.pin_d6 = XIAO_CAMERA_D6;
        camera_config.pin_d7 = XIAO_CAMERA_D7;

        camera_config.pin_vsync = XIAO_CAMERA_VSYNC;
        camera_config.pin_href = XIAO_CAMERA_HSYNC;
        camera_config.pin_pclk = XIAO_CAMERA_PCLK;
        camera_config.xclk_freq_hz = XIAO_CAMERA_XCLK_FREQ;
        camera_config.ledc_timer = XIAO_LEDC_TIMER;
        camera_config.ledc_channel = XIAO_LEDC_CHANNEL;
        camera_config.fb_location = CAMERA_FB_IN_PSRAM;
        
        camera_config.sccb_i2c_port = I2C_NUM_0;
        
        camera_config.pixel_format = PIXFORMAT_RGB565;
        camera_config.frame_size = FRAMESIZE_240X240;
        camera_config.jpeg_quality = 12;
        camera_config.fb_count = 1;
        camera_config.grab_mode = CAMERA_GRAB_WHEN_EMPTY;
        
        camera_ = new Esp32Camera(camera_config);

        Settings settings("sparkbot", false);
        // 考虑到部分复刻使用了不可动摄像头的设计，默认启用翻转
        bool camera_flipped = static_cast<bool>(settings.GetInt("camera-flipped", 1));
        camera_->SetHMirror(camera_flipped);
        camera_->SetVFlip(camera_flipped);
    }

    

public:
    EspXiaoBot() : boot_button_(BOOT_BUTTON_GPIO) {
        InitializeSpi();
        InitializeDisplay();
        InitializeButtons();
        InitializeCamera();
        //GetBacklight()->RestoreBrightness();
    }

    virtual AudioCodec* GetAudioCodec() override {
        static NoAudioCodecSimplexPdm audio_codec(AUDIO_INPUT_SAMPLE_RATE, AUDIO_OUTPUT_SAMPLE_RATE,
            AUDIO_I2S_SPK_GPIO_BCLK, AUDIO_I2S_SPK_GPIO_LRCK, AUDIO_I2S_SPK_GPIO_DOUT,
            AUDIO_I2S_MIC_GPIO_SCK, AUDIO_I2S_MIC_GPIO_DIN);
        return &audio_codec;
    }
    

    virtual Display* GetDisplay() override {
        return display_;
    }
/*
    virtual Backlight* GetBacklight() override {
        static PwmBacklight backlight(DISPLAY_BACKLIGHT_PIN, DISPLAY_BACKLIGHT_OUTPUT_INVERT);
        return &backlight;
    }
*/
    virtual Camera* GetCamera() override {
        return camera_;
    }
};

DECLARE_BOARD(EspXiaoBot);
